package com.bawei.auth.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.bawei.auth.form.LoginResponse;
import com.bawei.common.core.constant.TokenConstants;
import com.bawei.common.core.domain.Result;
import com.bawei.common.core.utils.JwtUtils;
import com.bawei.common.core.utils.msg.MsgUtil;
import com.bawei.common.core.utils.uuid.IdUtils;
import com.bawei.common.core.utils.uuid.UUID;
import com.bawei.mall.user.remote.api.IRemoteUserService;
import com.bawei.system.domain.model.User;
import com.bawei.system.remote.api.RemoteUserService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import com.bawei.common.core.constant.Constants;
import com.bawei.common.core.constant.SecurityConstants;
import com.bawei.common.core.constant.UserConstants;
import com.bawei.common.core.domain.R;
import com.bawei.common.core.enums.UserStatus;
import com.bawei.common.core.exception.ServiceException;
import com.bawei.common.core.utils.StringUtils;
import com.bawei.common.security.utils.SecurityUtils;
import com.bawei.system.domain.SysUser;
import com.bawei.system.domain.model.LoginUser;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

/**
 * 登录校验方法
 *
 * @author bawei
 */
@Component
public class SysLoginService {
    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysRecordLogService recordLogService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MsgUtil msgUtil;

    @Autowired
    private IRemoteUserService iremoteUserService;


    /**
     * 用户名登录
     */
    public LoginUser login(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password)) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户/密码必须填写");
            throw new ServiceException("用户/密码必须填写");
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户密码不在指定范围");
            throw new ServiceException("用户密码不在指定范围");
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户名不在指定范围");
            throw new ServiceException("用户名不在指定范围");
        }
        // 查询用户信息
        R<LoginUser> userResult = remoteUserService.getUserInfo(username, SecurityConstants.INNER);

        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在");
            throw new ServiceException("登录用户：" + username + " 不存在，注册一下吧");
        }

        if (R.FAIL == userResult.getCode()) {
            throw new ServiceException(userResult.getMsg());
        }

        LoginUser userInfo = userResult.getData();
        SysUser user = userResult.getData().getSysUser();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
            throw new ServiceException("对不起，您的账号：" + username + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            throw new ServiceException("对不起，您的账号：" + username + " 已停用");
        }
        passwordService.validate(user, password);
        recordLogService.recordLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功");
        return userInfo;
    }

    /**
     * 手机号登录
     */
    public LoginUser loginPhone(String phonenumber, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(phonenumber, password)) {
//            recordLogService.recordLogininfor(phonenumber, Constants.LOGIN_FAIL, "用户手机号/密码必须填写");
            throw new ServiceException("手机号/密码必须填写");
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
//            recordLogService.recordLogininfor(phonenumber, Constants.LOGIN_FAIL, "用户密码不在指定范围");
            throw new ServiceException("用户密码不在指定范围");
        }
        // 用户名不在指定范围内 错误
        if (phonenumber.length() != UserConstants.USERNAME_LENGTH) {
//            recordLogService.recordLogininfor(phonenumber, Constants.LOGIN_FAIL, "用户名不在指定范围");
            throw new ServiceException("手机号不在指定范围");
        }
        // 查询用户信息
        R<LoginUser> userResult = remoteUserService.getUserPhoneInfo(phonenumber, SecurityConstants.INNER);

        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData())) {
//            recordLogService.recordLogininfor(phonenumber, Constants.LOGIN_FAIL, "登录用户不存在");
            throw new ServiceException("登录手机号：" + phonenumber + " 不存在，注册一下吧");
        }

        if (R.FAIL == userResult.getCode()) {
            throw new ServiceException(userResult.getMsg());
        }

        LoginUser userInfo = userResult.getData();
        SysUser user = userResult.getData().getSysUser();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
//            recordLogService.recordLogininfor(phonenumber, Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
            throw new ServiceException("对不起，您的账号：" + phonenumber + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
//            recordLogService.recordLogininfor(phonenumber, Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            throw new ServiceException("对不起，您的账号：" + phonenumber + " 已停用");
        }
        passwordService.validate(user, password);
//        recordLogService.recordLogininfor(phonenumber, Constants.LOGIN_SUCCESS, "登录成功");
        return userInfo;
    }


    /**
     * 根据手机号发送验证码
     * @param phone
     * @return
     */
    public String sendMsg(String phone) {
        if (!validateTel(phone)){
            throw new RuntimeException("手机号格式不正确");
        }
        if (StringUtils.isBlank(phone)){
            throw new RuntimeException("手机号不能为空");
        }
        //远程调用 查询数据库 用户是否存在
        SysUser sysUser = remoteUserService.findSysUserByPhone(phone).getData();
        //判断是否存在
        if (ObjectUtils.isEmpty(sysUser)){
            throw new RuntimeException("用户不存在请注册");
        }
        //判断验证码是否存在，存在则不发送
        if (redisTemplate.hasKey(phone)){
            throw new RuntimeException("60s内不允许重复发送，请稍后重试");
        }
        //生成随机四位数验证码
        Random random = new Random();
        String code = String.valueOf(random.nextInt(9000) + 1000);
        //发送验证码
        String msg = msgUtil.sendMsg(phone, code);
        //判断是否成功
        if (!msg.contains("成功")){
            throw new RuntimeException("发送失败");
        }
        //成功则存入redis 设置过期时间为60s
        redisTemplate.opsForValue().set(phone,code,60, TimeUnit.SECONDS);
        return code;
    }


    public void logout(String loginName) {
        recordLogService.recordLogininfor(loginName, Constants.LOGOUT, "退出成功");
    }

    /**
     * 注册
     */
    public void register(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password)) {
            throw new ServiceException("用户/密码必须填写");
        }
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            throw new ServiceException("账户长度必须在2到20个字符之间");
        }
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            throw new ServiceException("密码长度必须在5到20个字符之间");
        }

        // 注册用户信息
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        sysUser.setNickName(username);
        sysUser.setPassword(SecurityUtils.encryptPassword(password));
        R<?> registerResult = remoteUserService.registerUserInfo(sysUser, SecurityConstants.INNER);

        if (R.FAIL == registerResult.getCode()) {
            throw new ServiceException(registerResult.getMsg());
        }
        recordLogService.recordLogininfor(username, Constants.REGISTER, "注册成功");
    }


    /**
     * 验证手机号格式
     *
     * @param tel
     * @return
     */
    public boolean validateTel(String tel) {
        Pattern compile = Pattern.compile("^(?:(?:\\+|00)86)?1(?:(?:3[\\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\\d])|(?:9[189]))\\d{8}$");
        return compile.matcher(tel).matches();
    }

    /**
     * 登录
     * @param username
     * @param password
     * @return
     */
    public Result<LoginResponse> userLogin(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password)) {
            throw new ServiceException("用户/密码必须填写");
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            throw new ServiceException("用户密码不在指定范围");
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            throw new ServiceException("用户名不在指定范围");
        }
        // 查询用户信息
        R<User> userResult = iremoteUserService.userLogin(username);
        User user = userResult.getData();

        // 获取token 使用JwtUtil
        HashMap<String, Object> map = new HashMap<>();
        map.put(IdUtils.fastUUID(),user.getUsername());
        String token = JwtUtils.createToken(map);
        redisTemplate.opsForValue().set("token",token);
        redisTemplate.opsForValue().set(token, JSONObject.toJSONString(user));
        LoginResponse loginResponse = new LoginResponse();
        loginResponse.setToken(token);
        loginResponse.setTokenHead(user.getUsername()+" ");
        return Result.ok(loginResponse);
    }


    /**
     * 获取用户信息
     */
    public User getInfo() {
        String token = redisTemplate.opsForValue().get("token");
        String cusUserJSONString = redisTemplate.opsForValue().get(token);
        User user = JSONObject.parseObject(cusUserJSONString, User.class);
        return user;
    }



//    public Map userLogin(String username, String password) {
//        //格式校验
//        if (StringUtils.isAnyBlank(username,password)){
//            throw new RuntimeException("用户名或密码不能为空");
//        }
//        //查询用户是否存在
//        R<User> userLogin = iremoteUserService.userLogin(username);
//
//        if (ObjectUtils.isEmpty(userLogin)){
//            throw new RuntimeException("用户不存在，请注册");
//        }
////        //密码加密
////        boolean passwordMatches = bCryptPasswordEncoder.matches(password, cusUser.getPassword());
////        if (!passwordMatches){
////            throw new RuntimeException("密码错误，请注册");
////        }
//        //token
//        Map<String, Object> tokenMap = new HashMap<>();
//        //UUID随机字符串
//        String userKey = UUID.randomUUID().toString().replace("", "");
//        //useKey存入redis
//        redisTemplate.opsForValue().set("user_key",userKey);
//        tokenMap.put("user_key",userKey);
//        String token = JwtUtils.createToken(tokenMap);
//
//        //返回值
//        HashMap<String, Object> map = new HashMap<>();
//        map.put(TokenConstants.TOKEN, token);
//        map.put(TokenConstants.TOKEN_HEAD, TokenConstants.PREFIX );
//        //存入redis
//        redisTemplate.opsForValue().set(TokenConstants.LOGIN_TOKEN_KEY + userKey, JSON.toJSONString(userLogin),30, TimeUnit.MINUTES);
//        return map;
//    }

    /**
     * 获取用户信息
     */
//    @Autowired
//    private HttpServletRequest request;
//    public User getInfo() {
//        //获取请求头
//        //String header = request.getHeader(TokenConstants.AUTHENTICATION);
//        String cacheUserKey = redisTemplate.opsForValue().get("user_key");
//        //获取userKey
//        //String userKey = JwtUtils.getUserKey(s);
//        //获取用户信息
//        String userStr = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + cacheUserKey);
//        //反序列化
//        User sysUser = JSON.parseObject(userStr, User.class);
//        return sysUser;
//    }


}
